package com.education.business.service.education;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.education.business.mapper.education.CourseSectionNodeMapper;
import com.education.business.service.BaseService;
import com.education.common.exception.BusinessException;
import com.education.common.utils.ResultCode;
import com.education.model.dto.CourseSectionNodeDto;
import com.education.model.entity.CourseSectionNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author zengjintao
 * @create_at 2021/10/6 11:00
 * @since version 1.0.3
 */
@Service
public class CourseSectionNodeService extends BaseService<CourseSectionNodeMapper, CourseSectionNode> {

    @Autowired
    private CourseInfoService courseInfoService;
    @Autowired
    private CourseSectionNodeMapper courseSectionNodeMapper;

    @Override
    @Transactional
    public boolean saveOrUpdate(CourseSectionNode courseSectionNode) {
        if (courseSectionNode.getId() == null) {
            courseInfoService.increaseSectionNodeNumber(courseSectionNode.getCourseId());
        }
        return super.saveOrUpdate(courseSectionNode);
    }

    @Transactional
    public void updateCourseSectionNode(CourseSectionNodeDto courseSectionNodeDto) {
        if (courseSectionNodeDto.getId() == null) {
            UpdateWrapper<CourseSectionNode> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("id", courseSectionNodeDto.getId())
                    .set("title", courseSectionNodeDto.getTitle())
                    .set("synopsis", courseSectionNodeDto.getSynopsis())
                    .set("enclosure", courseSectionNodeDto.getEnclosure())
                    .set("video_info", courseSectionNodeDto.getVideoInfo());
            courseSectionNodeMapper.update(null,updateWrapper);
        }
    }
    @Transactional
    public void deleteById(Integer id) {
        CourseSectionNode courseSectionNode = courseSectionNodeMapper.selectById(id);
        if(courseSectionNode == null){
            throw new BusinessException(new ResultCode(ResultCode.FAIL, "课时不存在,请刷新重试"));
        }
        // 课程信息课时数-1
        courseInfoService.decreaseSectionNodeNumber(courseSectionNode.getCourseId());
        // 删除课时信息
        courseSectionNodeMapper.deleteById(id);
    }
}
